var allProductDOM;
var xmlDOM;
sessionStorage.numOfProduct = 0;

function checkExist(productId, price,quantity){
    if(xmlDOM != null){
        var childs = xmlDOM.firstChild.childNodes;
        for(var i=0;i<childs.length;i++){
            var proID = childs[i].firstChild.firstChild.nodeValue;
            if(proID == productId){
                var nodeQty = childs[i].firstChild.nextSibling.nextSibling.nextSibling;
                var qty = parseInt(nodeQty.firstChild.nodeValue) + quantity;
                nodeQty.firstChild.nodeValue = qty;
                var nodeSubPrice = nodeQty.nextSibling;
                nodeSubPrice.firstChild.nodeValue = parseFloat(price) * qty;
                sessionStorage.xmldom = convertText(xmlDOM);
                return true;
            }
        }
    }
    return false;
}

function addToCart(productId,name,price,quantity,image){
    var xmlDetailHttp= null;
    try {
        xmlDetailHttp = XMLHttpRequest();
    }catch(e){
        try{
            xmlDetailHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
            xmlDetailHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if(xmlDetailHttp==null){
        alert("Your browser does not support AJAX!")
        return;
    }
    try{
        var url= "CustomerController?action=checkLoginFinish";
        xmlDetailHttp.open("GET",url,true);
        xmlDetailHttp.send(null);
        // get response o SearchHotelServlet action=ViewDetail
        xmlDetailHttp.onreadystatechange = function()
        {
            if(xmlDetailHttp.readyState==4 && xmlDetailHttp.status==200){
                var check = xmlDetailHttp.responseText;
                if(check == 'true') {
                    sessionStorage.numOfProduct = parseInt(sessionStorage.numOfProduct)+quantity;
                    sessionStorage.xmldom ="<cart>";
                    sessionStorage.xmldom +="<productId>"+productId+"</productId>";
                    sessionStorage.xmldom +="<name>"+name+"</name>";
                    sessionStorage.xmldom +="<price>"+price+"</price>";
                    sessionStorage.xmldom +="<quantity>"+quantity+"</quantity>";
                    sessionStorage.xmldom +="<subtotal>"+price*quantity+"</subtotal>";
                    sessionStorage.xmldom +="<image>"+image+"</image>";
                    sessionStorage.xmldom +="</cart>";
                    if(xmlDOM == null){
                        sessionStorage.xmldom ='<carts>'+sessionStorage.xmldom+"</carts>";
                        xmlDOM = stringToXML(sessionStorage.xmldom);
                    }else{
                        if(!checkExist(productId, price, quantity)){
                            var childN = stringToXML(sessionStorage.xmldom).documentElement;
                            xmlDOM.documentElement.appendChild(childN);
                        }
                    }
                    sessionStorage.xmldom = convertText(xmlDOM);
                    document.getElementById("cart-total").innerHTML = sessionStorage.numOfProduct + " Product(s)";
                    loadXML('xsl/cart.xsl', function complete(xsltDOM) {
                        transformXMLwithXSLT(xmlDOM,xsltDOM,'cart_content');
                    });
                    document.getElementById("cart").focus();
                    window.scrollTo(0,0);
                }else if (check == 'false') {
                    window.scrollTo(0,0);
                    document.getElementById("txtUsername").focus();
                }
            }
        }
    }catch(e){
        alert("error: "+ e);
    }

}

function loadCart(){
    if(sessionStorage.xmldom){
        xmlDOM = stringToXML(sessionStorage.xmldom);
        sessionStorage.numOfProduct = parseInt(GetNumOfProduct(xmlDOM));
        document.getElementById("cart-total").innerHTML = sessionStorage.numOfProduct + " Product(s)";
        loadXML('xsl/cart.xsl', function complete(xsltDOM) {
            transformXMLwithXSLT(xmlDOM,xsltDOM,'cart_content');
        });
    }
}

function GetNumOfProduct(doc){
    var childs = doc.firstChild.childNodes;
    sessionStorage.numOfProduct = 0;
    for(var i=0;i<childs.length;i++){
        var qtyNode = childs[i].firstChild.nextSibling.nextSibling.nextSibling;
        sessionStorage.numOfProduct = parseInt(sessionStorage.numOfProduct)+ parseInt(qtyNode.firstChild.nodeValue);
    }
    return sessionStorage.numOfProduct;
}

function deleteProduct(productId){
    if(xmlDOM){
        var childs = xmlDOM.firstChild.childNodes;
        for(var i=0;i<childs.length;i++){
            var proID = childs[i].firstChild.firstChild.nodeValue;
            if(proID == productId){
                xmlDOM.firstChild.removeChild(childs[i]);
                sessionStorage.xmldom = convertText(xmlDOM);
                if(xmlDOM.firstChild.childNodes.length == 0){
                    sessionStorage.numOfProduct = 0;
                    document.getElementById("cart-total").innerHTML = sessionStorage.numOfProduct + " Product(s)";
                    document.getElementById('cart_content').innerHTML = "Your Cart is empty !!!";
                }else{
                    loadCart();
                }
                return;
            }
        }
    }
}

function GetXmlHttpObject(){
    var xmlHttp = null;
    try{
        xmlHttp = new XMLHttpRequest();
    //        xmlHttp = document.XMLHttpRequest();
    }catch(e){
        try{
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function transformXMLwithXSLT(doc,xsltDOM,idElement){
    var out;
    try{
        if(window.ActiveXObject){
            out = doc.transformNode(xsltDOM);
        }else{
            var xsltProcessor=new XSLTProcessor();
            xsltProcessor.importStylesheet(xsltDOM);
            var xsltFrag = xsltProcessor.transformToFragment(doc,document);
            out = convertText(xsltFrag);
        }
        document.getElementById(idElement).innerHTML = out;
    } catch (exception) {
        if (typeof (exception) == "object") {
            if (exception.message) {
                alert(exception.message);
            }
        } else {
            alert(exception);
        }
    }
}

function loadXML(path, callback) {
    var request;
    // Create a request object. Try Mozilla / Safari method first.
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    // If that doesn't work, try IE methods.
    } else if (window.ActiveXObject) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
            }
        }
    }
    // If we couldn't make one, abort.
    if (!request) {
        window.alert("No ajax support.");
        return false;
    }

    // Upon completion of the request, execute the callback.
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status === 200) {
                callback(request.responseXML);
            } else {
                window.alert("Could not load " + path);
            }
        }
    };

    request.open("GET", path);
    request.send();
}

function stringToXML(text){
    var doc;
    try{
        if(window.ActiveXObject){
            doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = 'false';
            doc.loadXML(text);

        }else{
            var parser = new DOMParser();
            doc = parser.parseFromString(text,'text/xml')
        }
    }catch(e){
        doc.load(text);
    }
    return doc;
}

function convertText(doc){
    var xmlContent;
    try{
        if(window.ActiveXObject){
            xmlContent = doc.documentElement.xml;
        }else{
            xmlContent = new XMLSerializer().serializeToString(doc);
        }
        return xmlContent;
    }catch(e){
        return "";
        e.toString();
    }
}

function getAllProducts(filename){
    loadXML(filename, function complete(result) {
        allProductDOM = result;
    });

}
function returnAllProductsDom(){
    return allProductDOM;
}

function productMouserOverCart(id){
    var childs;
    var domxml;
    if (allProductDOM != null){
        childs = allProductDOM.childNodes;
        for (i = 0; i < childs.length; i++) {
            if (childs[i].nodeName == 'products'){
                childs = childs[i].childNodes;
                break;
            }
        }
        for (i = 0; i < childs.length; i++) {
            var childs2 = childs[i].childNodes;
            for (j = 0; j < childs2.length; j++) {
                if (childs2[j].nodeName == 'productID'){
                    if (childs2[j].textContent == id){
                        domxml = childs[i];
                        break;
                    }
                    continue;
                }
            }
        }
        domxml = stringToXML(convertText(domxml));
        var xsltFile="xsl/productDetail.xsl";
        if (domxml!=null){
            loadXML(xsltFile, function complete(result) {
                var xsl = result;
                transformXMLwithXSLT(domxml, xsl, 'Product-Detail')
                document.getElementById("Product-Detail").style.display="block";
            });
        }
    }
    //lay vi tri con chuot
    document.onmousemove=setTooltipPos;
}
//        function A(){document.getElementById("Product-Detail").style.display='none';}
function productMouseOut(){
    //setInterval(A, 1000);
    //sleep(1);
    document.getElementById("Product-Detail").style.display='none';
//setTimeout("A()", 400);
}
function setTooltipPos(e){
    try{
        if(!e) e = event ;
        var mp = getMousePosition(e);
        if (mp.x > 610){
            document.getElementById("Product-Detail").style.left=(mp.x-610)+'px';
        }else{
            document.getElementById("Product-Detail").style.left=(mp.x+10)+'px';
        }
        document.getElementById("Product-Detail").style.top=(mp.y+10)+'px';
    }catch(e){
        alert(e);
    }
}
function getMousePosition(e){
    return e.pageX?{
        'x':e.pageX,
        'y':e.pageY
    }:{
        'x':e.clientX+document.documentElement.scrollLeft+document.body.scrollLeft,
        'y':e.clientY+document.documentElement.scrollTop+document.body.scrollTop
    };
}
        /// chua su dung